/**
 * @author  weigao<weigao@iflytek.com>
 *
 * @version 1.0.0
 */
package com.iflytek.uoamp.agent.monitor.dump;

import com.iflytek.uoamp.agent.core.sender.monitorsender.monitorinterface.IItem;
import com.iflytek.uoamp.agent.core.sender.monitorsender.responseObj.NewVersion;
import com.iflytek.uoamp.agent.monitor.dump.obj.DumpTask;
import com.iflytek.uoamp.agent.monitor.dump.obj.TaskPing;
import com.iflytek.uoamp.agent.monitor.mcagent.MCAgentConfig;
import com.iflytek.uoamp.agent.monitor.mcagent.MCAgentMain;

import org.apache.log4j.Logger;

import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;

public class DumpTaskGetter implements Runnable{

	public static final int DUMP_FINISH_DELED = -2;
	public static final int DUMP_FINISH_DEL = -1;
	public static final int DUMP_FINISH_NOTSTART = 0;
	public static final int DUMP_FINISH_READY = 1;
	public static final int DUMP_FINISH_DUMPFINISH = 2;
	public static final int DUMP_FINISH_UPDATEING = 3;
	public static final int DUMP_FINISH_FINISH = 4;
	public static final int DUMP_FINISH_NOMONITOR = 5;
	public static final int DUMP_UPLOAD_ERROR = 6;
	public static final int DUMP_CANCEL = 7;
	public static final int DUMP_TIME_OVER = 8;
	public static final int DUMP_CANCEL_FINISH = 9;
	
	public static final int DUMP_TASK_TYPE_ONLYONE = -1;
	public static final int DUMP_TASK_TYPE_NOW = -2;
	public static final int DUMP_TASK_TYPE_CANCEL = -3;

	private static DumpTaskGetter instance = new DumpTaskGetter();
	private Queue<String> cancelList = new LinkedBlockingQueue<String>();
	private Queue<String> delList = new LinkedBlockingQueue<String>();

	private Map<String,DumpTask> taskMap = new ConcurrentHashMap<String,DumpTask>();
	private DumpTaskGetter(){
		
	}
	
	public static DumpTaskGetter getInstance(){
		return instance;
	}
	
	public Map<String,DumpTask> getTaskMap(){
		return taskMap;
	}



	/**
	 * 从服务端拉取task的列表
	 * @return
	 */
	private List<DumpTask> getDumpTasks(){
		List<DumpTask> list = new LinkedList<DumpTask>();
		if(!MCAgentMain.getSenderClient().getConfig().isUseHttp()){
			Map<String, String> taskProces = getDumpTaskStatus();
			IItem ping = new TaskPing(MCAgentConfig.getInstance().getMonitoredPointIp(),taskProces);
			Object result = MCAgentMain.getSenderClient().sendBySafe(ping);
			if(result!=null && result instanceof List){
				List<NewVersion> tempList = (List<NewVersion>)result;
				Logger.getRootLogger().info("INFO | get dump task success and get "+tempList.size()+" task");
				for(NewVersion cur:tempList){
					Map<String,String> keys = cur.getHeaders();
					DumpTask task = new DumpTask();
					task.setValues(keys);
					list.add(task);
				}
			}
		}
		return list;
	}
	
	/**
	 * 获取task任务的状态并删除无用任务；
	 */
	private Map<String,String> getDumpTaskStatus(){
		Map<String,String> taskStatus = new HashMap<String,String>();
		//清除终止任务
		while(!cancelList.isEmpty()){
			String cancelID = cancelList.poll();
			taskStatus.put(cancelID, DumpTaskGetter.DUMP_CANCEL_FINISH + "");
			taskMap.remove(cancelID);
		}
		//清除删除任务；主要是页面显示不同；删除任务在页面不会显示；
		while(!delList.isEmpty()){
			String cancelID = delList.poll();
			taskStatus.put(cancelID, DumpTaskGetter.DUMP_FINISH_DELED + "");
			taskMap.remove(cancelID);
		}

		Iterator<Entry<String, DumpTask>> it = taskMap.entrySet().iterator();
		while(it.hasNext()){
			Entry<String, DumpTask> entry = it.next();
			DumpTask task = entry.getValue();
			if(task.isUpdate()){
				int stat = task.getFinsh_stat();
				taskStatus.put(task.getTask_id()+"", stat+"");
				task.setUpdate(false);

				if(task.getTask_type()== DumpTaskGetter.DUMP_TASK_TYPE_NOW || task.getTask_type()== DumpTaskGetter.DUMP_TASK_TYPE_ONLYONE){
					if(stat>= DumpTaskGetter.DUMP_FINISH_FINISH){
						it.remove();
					}
				}
			}

			if(task.getFinsh_stat()== DumpTaskGetter.DUMP_TIME_OVER){
				it.remove();
			}
		}
		return taskStatus;
	}
	
	@Override
	public void run() {
		try {
			List<DumpTask> list = getDumpTasks();
			for(DumpTask task:list){
				//取消任务
				if(task.getFinsh_stat()==DUMP_CANCEL){
					DumperTaskRunner.getInstance().stopThread(task.getTask_id() + "");
					cancelList.offer(task.getTask_id() + "");
				}else if(task.getFinsh_stat()==DUMP_FINISH_DEL){
					DumperTaskRunner.getInstance().stopThread(task.getTask_id() + "");
					delList.offer(task.getTask_id()+"");
				}else{
					//需要保证不会有下发的ID及不是取消任务；又需要更新
					task.setFinsh_stat(DumpTaskGetter.DUMP_FINISH_READY);
					taskMap.put(task.getTask_id()+"", task);
				}
			}
			
		} catch (Exception e) {
			Logger.getRootLogger().info(e.getMessage(),e);
		}
	}

}
